package com.qianji.petmall.ware.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liang zai
 * @date 2022/5/11 12:08
 * @description
 */
@Configuration
public class MyMQConfig {
    /**
     * 创建队列，交换机，延迟队列，绑定关系 的configuration
     * 不会重复创建覆盖
     * 1、第一次使用队列【监听】的时候才会创建
     * 2、Broker没有队列、交换机才会创建
     */
//    @RabbitListener(queues = "stock.release.stock.queue")
//    public void listen(Channel channel, Message message) throws IOException {
//        System.out.println("收到库存解锁消息,准备解锁库存:------>");
//        long deliveryTag = message.getMessageProperties().getDeliveryTag();
//        channel.basicAck(deliveryTag,false);
//    }



    Map<String, Object> arguments = new HashMap<>();
    /**
     * 延时队列
     * @return
     */
    @Bean
    public Queue stockDelayQueue(){
        arguments.put("x-message-ttl",120000);
        arguments.put("x-dead-letter-exchange","stock-event-exchange");
        arguments.put("x-dead-letter-routing-key","stock.release");
        Queue queue = new Queue("stock.delay.queue",true,false,false,arguments);
        return queue;
    }

    /**
     * 普通队列
     * @return
     */
    @Bean
    public Queue stockReleaseStockQueue(){
        Queue queue = new Queue("stock.release.stock.queue",true,false,false,null);
        return queue;
    }

    /**
     * 交换机
     * @return
     */
    @Bean
    public Exchange stockEventExchange(){
        TopicExchange topicExchange = new TopicExchange("stock-event-exchange",true,false);
        return topicExchange;
    }
    /**
     * 交换机与延迟队列绑定
     * @return
     */
    @Bean
    public Binding stockLockedBinding(){
        Binding binding = new Binding("stock.delay.queue", Binding.DestinationType.QUEUE,
                "stock-event-exchange", "stock.locked",null);
        return binding;
    }
    /**
     * 交换机与普通队列绑定
     * @return
     */
    @Bean
    public Binding stockLocked(){
        Binding binding = new Binding("stock.release.stock.queue", Binding.DestinationType.QUEUE,
                "stock-event-exchange", "stock.release.#",null);
        return binding;
    }
}
